<template>
	<view class="cart-page">
		<!-- 顶部标题和搜索框 -->
		<view class="header">
			<view class="title">购物车</view>
			<view class="search-box">
				<uni-icons type="search" size="20" color="#999"></uni-icons>
				<input type="text" placeholder="搜索商品" />
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-box">
			<uni-loading type="circle" size="36"></uni-loading>
			正在加载购物车...
		</view>

		<!-- 空状态 -->
		<view v-else-if="cartList.length === 0" class="empty-box">
			<image src="/static/empty-cart.png" class="empty-image"></image>
			<text class="empty-text">购物车还是空的哦~</text>
		</view>

		<!-- 商品列表 -->
		<view v-else class="product-list">
			<view class="product-item" v-for="(item, index) in cartList" :key="item.cartId">
				<checkbox :checked="item.checked" color="#FFA500" @click="toggleCheck(index)" />
				<image :src="item.image" class="product-image" mode="aspectFill"></image>
				<view class="product-info">
					<text class="product-name">{{ item.goodsName }}</text>
					<text class="product-price">￥{{ item.goodsPrice.toFixed(2) }}</text>
					<view class="product-actions">
						<uni-icons type="minus" size="20" @click="changeQuantity(index, -1)"
							:disabled="item.addgoodsQuantity <= 1"></uni-icons>
						<text class="quantity">{{ item.addgoodsQuantity }}</text>
						<uni-icons type="plus" size="20" @click="changeQuantity(index, 1)"
							:disabled="item.addgoodsQuantity >= item.stock"></uni-icons>
					</view>
				</view>
				<uni-icons type="trash" size="24" color="#999" @click="deleteItem(item.cartId)"></uni-icons>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view v-if="cartList.length > 0" class="footer">
			<view class="left-section">
				<checkbox :checked="isAllChecked" color="#FFA500" @click="toggleAllCheck" />
				<text class="select-all">全选</text>
			</view>
			<view class="right-section">
				<view class="total-price">
					合计：<text class="price">￥{{ totalPrice.toFixed(2) }}</text>
				</view>
				<button class="settle-btn" @click="handleSettlement">
					结算({{ checkedCount }})
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartList: [],
				loading: true,
				userId: null,
				error: null
			};
		},
		computed: {
			totalPrice() {
				return this.cartList.reduce((total, item) => {
					return item.checked ? total + item.goodsPrice * item.addgoodsQuantity : total;
				}, 0);
			},
			checkedCount() {
				return this.cartList.filter(item => item.checked).length;
			},
			isAllChecked() {
				return this.cartList.length > 0 && this.cartList.every(item => item.checked);
			}
		},
		onShow() {
			this.loadCartData();
		},
		async onLoad() {
			await this.loadCartData();
		},
		methods: {
			async loadCartData() {
				try {
					// 获取用户信息
					const userRes = await uni.request({
						url: 'http://localhost:8080/system/user/profile',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});
					if (userRes.data.code !== 200) throw new Error('获取用户信息失败');
					this.userId = userRes.data.data.userId;

					// 获取购物车列表
					const cartRes = await uni.request({
						url: 'http://localhost:8080/goodscart/goodscart/list',
						data: {
							userId: this.userId
						},
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});

					// 获取商品详情
					this.cartList = await Promise.all(
						cartRes.data.rows.map(async cart => {
							const goodsRes = await uni.request({
								url: `http://localhost:8080/goods/goods/${cart.goodsId}`,
								header: {
									'Authorization': uni.getStorageSync('token')
								}
							});
							return {
								...cart,
								image: `http://localhost:8080${goodsRes.data.data.goodsImage1}`,
								goodsName: goodsRes.data.data.goodsName,
								goodsPrice: goodsRes.data.data.goodsPrice,
								stock: goodsRes.data.data.stockQuantity,
								checked: false
							};
						})
					);
				} catch (error) {
					this.error = error.message;
					uni.showToast({
						title: `加载失败: ${this.error}`,
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			toggleCheck(index) {
				this.cartList[index].checked = !this.cartList[index].checked;
			},

			toggleAllCheck() {
				const newState = !this.isAllChecked;
				this.cartList.forEach(item => (item.checked = newState));
			},

			async changeQuantity(index, delta) {
				const item = this.cartList[index];
				let newQuantity = item.addgoodsQuantity + delta;

				// 限制数量不为0或负数
				if (newQuantity < 1) {
					newQuantity = 1;
				}

				try {
					const res = await uni.request({
						url: `http://localhost:8080/goodscart/goodscart`,
						method: 'PUT',
						header: {
							'Authorization': uni.getStorageSync('token')
						},
						data: {
							cartId: item.cartId,
							addgoodsQuantity: newQuantity
						}
					});

					if (res.data.code === 200) {
						this.cartList[index].addgoodsQuantity = newQuantity;
					}
				} catch (error) {
					uni.showToast({
						title: '修改数量失败',
						icon: 'none'
					});
				}
			},

			async deleteItem(cartId) {
				try {
					const res = await uni.request({
						url: `http://localhost:8080/goodscart/goodscart/${cartId}`,
						method: 'DELETE',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});

					if (res.data.code === 200) {
						this.cartList = this.cartList.filter(item => item.cartId !== cartId);
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				}
			},

			// 修改后的结算方法
			handleSettlement() {
				const selectedItems = this.cartList.filter(item => item.checked);
				if (selectedItems.length === 0) {
					return uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					});
				}

				const orderData = selectedItems.map(item => ({
					goodsId: item.goodsId,
					quantity: item.addgoodsQuantity,
					cartId: item.cartId,
					goodsPrice: item.goodsPrice
				}));

				// 跳转订单页面
				uni.navigateTo({
					url: `/pages/order-payment/order-payment?items=${encodeURIComponent(
            JSON.stringify(orderData)
          )}&userId=${this.userId}`
				});
			}
		}
	};
</script>

<style scoped>
	/* 保持原有样式不变 */
	.cart-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		position: relative;
		background-color: #FFF8F0;
	}

	.header {
		/* display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20px;
		border-bottom: 1px solid #eee;
		background-color: #FFF8F0;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2); */
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		/* border-bottom: 1px solid #eee; */
		background-color: white;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
	}

	.title {
		font-size: 18px;
		font-weight: bold;
		/* color: orange; */
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 15px;
		padding: 5px 10px;

		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.product-item {
		display: flex;
		align-items: center;
		padding: 10px;
		background-color: #fff;
		margin-bottom: 10px;
		border-radius: 5px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 20px;
		background-color: #fff;
		border-top: 1px solid #eee;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}


	.search-box input {
		margin-left: 5px;
		font-size: 14px;
	}

	.product-list {
		flex: 1;
		overflow-y: auto;
		padding: 10px;
		padding-bottom: 50px;
	}


	.product-image {
		width: 80px;
		height: 80px;
		margin-right: 10px;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.product-name {
		/* font-size: 16px;
		margin-bottom: 5px; */

		font-size: 16px;
		margin-bottom: 5px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}

	.product-price {
		font-size: 14px;
		color: #f40;
		white-space: normal;
		/* 允许换行 */
		word-wrap: break-word;
		/* 长词换行 */
		word-break: break-all;
		/* 中文换行 */
	}

	.product-actions {
		display: flex;
		align-items: center;
	}

	.quantity {
		margin: 0 10px;
		font-size: 16px;
	}


	.select-all {
		margin-left: 10px;
	}

	.total-price {
		flex: 1;
		text-align: right;
		margin-right: 20px;
	}

	.price {
		color: #f40;
		font-weight: bold;
	}

	.settle-btn {
		background-color: #f40;
		color: #fff;
		border-radius: 20px;
		padding: 5px 20px;
		font-size: 14px;
	}

	.tabbar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-top: 1px solid #eee;
	}

	/* 原有样式保持不变，新增以下样式 */
	.loading-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx;
		color: #888;
	}

	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 0;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}

	.product-item {
		position: relative;
		padding: 20rpx;
	}

	/* 调整 product-info 样式以显示完整 goods-price */
	.product-info {
		/* flex: 1; */
		width: 50px;
		margin: 0 20rpx;
		white-space: normal;
		/* 允许换行 */
		word-wrap: break-word;
		/* 长词换行 */
		word-break: break-all;
		/* 中文换行 */
	}

	.product-actions {
		display: flex;
		align-items: center;
		margin-top: 10rpx;
	}

	.product-actions text {
		margin: 0 20rpx;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background: #fff;
		border-top: 1rpx solid #eee;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
		 /* height: 150px; */
		 
		 /* 在h5运行的时候会出现底部tabbr重叠的问题 注释掉即可 */
		 /* padding-bottom: 60px; */
	}

	.left-section {
		display: flex;
		align-items: center;
	}

	.right-section {
		display: flex;
		align-items: center;
	}

	.settle-btn {
		background: linear-gradient(90deg, #ff5500, #ff3000);
		color: #fff;
		padding: 0rpx 45rpx;
		border-radius: 40rpx;
	}
</style>